#!/bin/bash
#
# clouddiy:         Starts the clouddiy if it hasn't been run before
#
# chkconfig: 35 99 95
#
# description:       Clouddiy is a bootstrap code to configure your system.
#                    If a machine is booted after install,
#                    It checks for the existence of an /var/run/clouddiy.
#                    If it find the lock file, start to install based on your order.
#                    1. install clouddiy package from internet
#                    2. run clouddiy 
#

VERSION=1.0
AUTHOR="Choonho Son"

PYTHON_VER=`python -c 'import sys
print ("%s.%s" % (sys.version_info[0], sys.version_info[1]))'`

LOCKFILE=/var/lock/clouddiy
PACKAGE="clouddiy-py"$PYTHON_VER".egg"
URL="http://conf.googlecode.com/files"


[ -z "$HOME" ] && export HOME=/

function download {
    TARGET=/tmp/$1
    if [ -f "$TARGET" ]; then
	logger "[clouddiy] $TARGET already exist"
	TIMESTAMP=`date +"%Y-%m-%d:%H:%M"`
	logger "[clouddiy] move to $TARGET.$TIMESTAMP"
	mv $TARGET $TARGET.$TIMESTAMP
    fi

    logger "[clouddiy] Download: $1"
    logger "[clouddiy] Target: $TARGET"
    NEW_URL=$URL/$1
    wget -t 3 -O $TARGET $NEW_URL

    if [ -f "$TARGET" ];
	then
	logger "[clouddiy] Install $TARGET"
	easy_install $TARGET
	else
	logger "[clouddiy] [ERROR] Failed to download $TARGET"
    fi
    
}



function run {
    logger "[clouddiy] run installer"
    EXECUTE=`python -c 'import clouddiy
clouddiy.run()'`

}

function info {
    logger "[clouddiy] ############################################"
    logger "[clouddiy] #  Cloud Do It Yourself (clouddiy)          "
    logger "[clouddiy] #  Version: $VERSION                   "
    logger "[clouddiy] #  Author : $AUTHOR       "
    logger "[clouddiy] #  Python : $PYTHON_VER   "
    logger "[clouddiy] ############################################"
}

info
#echo "Python Version:$PYTHON_VER"

case "$1" in
 start)

	if [ -f "$LOCKFILE" ];
	then
	    logger "[clouddiy] Lock $LOCKFILE exists."
	    logger "[clouddiy] Remove lock file : $LOCKFILE"
	    rm -f $LOCKFILE
	    logger "[clouddiy] Start to install......"
	    download $PACKAGE
	    run
	else
	    logger "[clouddiy] Lock $LOCKFILE does not exist."
	    logger "[clouddiy] It's OK to remove itself..."
	    exit 0
	fi
	;;

 restart)
        logger "[clouddiy] Restarting Cloud-DIY ..."
        touch $LOCKFILE
	$0 start
	;;
 stop)
	logger "[clouddiy] Remove lock file : $LOCKFILE"
	rm -f $LOCKFILE
	;;

 *)
   logger $"Usage: $0 {start|stop|restart}"
   RETVAL=1
esac

exit $RETVAL
